package xin.ryven.car.android.adapter

import android.content.Context
import android.graphics.drawable.AnimationDrawable
import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.PopupMenu
import android.widget.Toast
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import xin.ryven.car.android.R
import xin.ryven.car.android.data.Music
import xin.ryven.car.android.databinding.ItemMusicBinding
import xin.ryven.car.android.utils.FileUtils
import xin.ryven.car.android.utils.FontUtils

class MusicAdapter(
    private val context: Context,
    private val onItemClick: (Music) -> Unit,
    private val onDownloadClick: (Music) -> Unit,
    private val onReDownloadClick: (Music) -> Unit,
    private val onDeleteClick: (Music) -> Unit
) : ListAdapter<Music, MusicAdapter.ViewHolder>(MusicDiffCallback()) {

    private val downloadProgress = mutableMapOf<Int, Int>()
    private val downloadingStates = mutableMapOf<Int, Boolean>()
    private var playingMusicId: Int? = null
    private var currentPlayingIndicator: ImageView? = null
    private var isPlaying = false

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val binding = ItemMusicBinding.inflate(
            LayoutInflater.from(parent.context),
            parent,
            false
        )
        return ViewHolder(binding)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bind(getItem(position))
    }

    override fun onBindViewHolder(
        holder: ViewHolder,
        position: Int,
        payloads: MutableList<Any>
    ) {
        if (payloads.isNotEmpty()) {
            // 如果是进度更新，只更新进度条
            val progress = payloads[0] as Int
            holder.updateProgress(progress)
        } else {
            super.onBindViewHolder(holder, position, payloads)
        }
    }

    fun updateDownloadProgress(musicId: Int, progress: Int) {
        downloadProgress[musicId] = progress
        // 使用 post 确保在主线程更新
        Handler(Looper.getMainLooper()).post {
            val position = currentList.indexOfFirst { it.id == musicId }
            if (position != -1) {
                notifyItemChanged(position, progress)
            }
        }
    }

    fun setDownloading(musicId: Int, isDownloading: Boolean) {
        downloadingStates[musicId] = isDownloading
        if (!isDownloading) {
            downloadProgress.remove(musicId)
        }
        Handler(Looper.getMainLooper()).post {
            val position = currentList.indexOfFirst { it.id == musicId }
            if (position != -1) {
                notifyItemChanged(position)
            }
        }
    }

    fun updateList(newList: List<Music>) {
        submitList(newList)
    }

    fun setPlayingMusic(music: Music?) {
        val oldPlayingId = playingMusicId
        playingMusicId = music?.id
        
        if (oldPlayingId != null) {
            notifyItemChanged(currentList.indexOfFirst { it.id == oldPlayingId })
        }
        if (playingMusicId != null) {
            notifyItemChanged(currentList.indexOfFirst { it.id == playingMusicId })
        }
    }

    fun updatePlayingState(musicId: Int, playing: Boolean) {
        isPlaying = playing
        Handler(Looper.getMainLooper()).post {
            val position = currentList.indexOfFirst { it.id == musicId }
            if (position != -1) {
                notifyItemChanged(position)
            }
        }
    }

    inner class ViewHolder(private val binding: ItemMusicBinding) : RecyclerView.ViewHolder(binding.root) {
        fun updateProgress(progress: Int) {
            binding.downloadProgressBg.apply {
                if (progress > 0 && progress < 100) {
                    visibility = View.VISIBLE
                    val params = layoutParams as FrameLayout.LayoutParams
                    params.width = (itemView.width * progress / 100)
                    layoutParams = params
                } else {
                    visibility = View.GONE
                }
            }
        }

        fun bind(music: Music) {
            binding.apply {
                tvTitle.text = music.name
                tvSinger.text = music.singer
                
                // 应用自定义字体
                xin.ryven.car.android.utils.FontUtils.apply(tvTitle)
                xin.ryven.car.android.utils.FontUtils.apply(tvSinger)

                val isDownloading = downloadingStates[music.id] == true
                val progress = downloadProgress[music.id] ?: 0
                val isDownloaded = FileUtils.isMusicFileExists(context, music)

                if (isDownloaded) {
                    btnDownload.visibility = View.GONE
                    downloadProgressBg.visibility = View.GONE
                } else if (isDownloading) {
                    btnDownload.visibility = View.GONE
                    updateProgress(progress)
                } else {
                    btnDownload.visibility = View.VISIBLE
                    downloadProgressBg.visibility = View.GONE
                }

                root.setOnClickListener {
                    bindingAdapterPosition.takeIf { it != RecyclerView.NO_POSITION }?.let {
                        if (isDownloaded) {
                            onItemClick(music)
                        } else if (!isDownloading) {
                            Toast.makeText(context, "请先下载歌曲", Toast.LENGTH_SHORT).show()
                        }
                    }
                }

                btnDownload.setOnClickListener {
                    if (!isDownloading) {
                        setDownloading(music.id, true)
                        updateProgress(0)
                        onDownloadClick(music)
                    }
                }

                if (music.id == playingMusicId) {
                    ivPlayingIndicator.visibility = View.VISIBLE
                    playingBackground.visibility = View.VISIBLE
                    val animDrawable = ivPlayingIndicator.drawable as? AnimationDrawable
                    if (isPlaying) {
                        animDrawable?.start()
                    } else {
                        animDrawable?.stop()
                    }
                } else {
                    ivPlayingIndicator.visibility = View.GONE
                    playingBackground.visibility = View.GONE
                    (ivPlayingIndicator.drawable as? AnimationDrawable)?.stop()
                }

                root.setOnLongClickListener {
                    showPopupMenu(it, music, isDownloaded)
                    true
                }
            }
        }

        private fun showPopupMenu(view: View, music: Music, isDownloaded: Boolean) {
            val popup = PopupMenu(context, view)
            popup.menuInflater.inflate(R.menu.menu_music_item, popup.menu)
            
            // 根据下载状态控制菜单项
            popup.menu.findItem(R.id.action_redownload).isVisible = isDownloaded
            popup.menu.findItem(R.id.action_delete).isVisible = isDownloaded

            popup.setOnMenuItemClickListener { item ->
                when (item.itemId) {
                    R.id.action_redownload -> {
                        onReDownloadClick(music)
                        true
                    }
                    R.id.action_delete -> {
                        onDeleteClick(music)
                        true
                    }
                    else -> false
                }
            }
            popup.show()
        }
    }
}

class MusicDiffCallback : DiffUtil.ItemCallback<Music>() {
    override fun areItemsTheSame(oldItem: Music, newItem: Music): Boolean {
        return oldItem.id == newItem.id
    }

    override fun areContentsTheSame(oldItem: Music, newItem: Music): Boolean {
        return oldItem == newItem
    }
} 